<?php
declare (strict_types = 1);

namespace app\admin\model;
use think\Model;

use  think\Facade\Cache;
/**
 * @mixin \think\Model
 */
class Menu extends Model
{
    protected $name="menu";


    public function getTreeMenu()
    {
        $tree = $this->order('parent_id asc, sort_number asc')->select()->toArray();
        return $this->makeTree($tree);
    }

    // 递归构建树
    public function makeTree($array, $parent_id = 0)
    {
        $tree = array();
        foreach($array as $key => $value) {
            if($value['parent_id'] == $parent_id) {
                $value['children'] = $this->makeTree($array, $value['id']);
                $tree[] = $value;
                unset($array[$key]);
            }
        }
        return $tree;
    }

    public function getMenu($roleId){
    /*    $data = Cache::get('menu');*/
        $data =[];
        if (!$data){
            $data = $this->where(['deleted' => 0])->order('sort_number','asc')->select()->toArray();
       /*     Cache::set('menu', $data);*/
        }
        if (!in_array(1,$roleId) ){
            $roleMenuModel  = new RoleMenu();

            $roleMenu =  $roleMenuModel->where('role_id' ,'in',$roleId )->select()->toArray();

            $menuId = array_column($roleMenu,'menu_id');
            foreach ($data as $key => $value){
                if (!in_array($value['menu_id'],$menuId)){
                    unset($data[$key]);
                }
            }
        }

        return  array_values($data);
    }
    public  function addMenu($data){
        $this->insert($data);
      /*  Cache::delete('menu');*/

    }



}



